﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

public static class ConvertData
{
    /// <summary>
    /// DataTable转换为json
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string ToJson(this DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder("{\"");
        jsonBuilder.Append(dt.TableName);
        jsonBuilder.Append("\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }

    public static string ToJson(this DataSet ds)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        foreach (DataTable dt in ds.Tables)
        {
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName);
            jsonBuilder.Append("\":");
            jsonBuilder.Append(dt.ToJson());
            jsonBuilder.Append("}");
        }
        return jsonBuilder.ToString();
    }
}
